# 引入django框架中http模块中HttpResponse函数
from django.http import HttpResponse
from django.shortcuts import render
from django.shortcuts import redirect
from mydjango.models import Users
from mydjango.models import Goods
from mydjango.models import Cars
import math

# 设置处理函数
def hw(request):
    return HttpResponse('<h1 align="center" style="color:red;">我带你们打</h1>')


def index(request):
    # name = request.GET.get('name')
    # name 值获取和session关联 uid是否存在
    if request.session.get('uid',None):
        # 有值 True 说明登录过
        Users.objects.filter(uid=request.session['uid'])[0].username
    else:
        # 无值 False 说明没登录过
        name=None

    stuname='weixm'
    grade=83
    good={'id':1,'name':'西瓜','imgsrc':'/static/img/lzx.jpg','price':3.9,'count':4}
    goods=[
        {'id': 1, 'name': '西瓜', 'imgsrc': '/static/img/lzx.jpg', 'price': 3.9, 'count': 4},
        {'id': 2, 'name': 'aa', 'imgsrc': '/static/img/lzx.jpg', 'price': 3.9, 'count': 4},
        {'id': 3, 'name': 'bb', 'imgsrc': '/static/img/lzx.jpg', 'price': 3.9, 'count': 4},
        {'id': 4, 'name': 'cc', 'imgsrc': '/static/img/lzx.jpg', 'price': 3.9, 'count': 4},
    ]
    #接收前端传递 keywords
    keywords = request.GET.get('keywords')
    if keywords:
        goods=Goods.objects.filter(name__contains=keywords)
    else:
        goods=Goods.objects.all()
    # 前端传递的页码列表 pagelist[1.2.3...]
    # 封装函数range（stand,end) 自动生成从start开始（包含）到end结束（不包含）的列表
    pagelist=range(1,math.ceil(len(goods)/5)+1)
    # 接收前端传递的页码参数

    page=request.GET.get('page')
    if page:
        # 有值 字符串转为整数
        page=int(page)
    else:
        # 无值默认展示第一页
        page=1
    # 截取数据查询的结果的前5个  列表切片
    goods = goods[5*(page-1):5*page]
    return render(request,"index.html",{'pagelist':pagelist,'goods':goods,"name":name,'stuname':stuname,'grade':grade,'good':good})

def login(request):
    if request.POST:
        username = request.POST.get('username')
        userpsd = request.POST.get('userpsd')
        result = Users.objects.filter(username=username,userpsd=userpsd)
        if result:
            #判断一下 当前有值的账号对应密码和前端发送的密码是否匹配
            if request[0].userpsd==userpsd:
                # return HttpResponse('登录成功')
                ##设置session会话存储 uid
                request.session['uid']=result[0].uid
                return redirect('/index/?name='+result[0].username)
            else:
                # 账号存在 密码错
                # 误
                return render(request,'login.html')
        else:
            # 账号不存在
            # return HttpResponse('登录失败')
            return render(request, 'register.html')
    return render(request,'login.html')

def register(request):
    if request.POST:
        username = request.POST.get('username')
        userpsd = request.POST.get('userpsd')
        #插入数据库
        ##将用户类实例化对象
        # user1 = Users(uid=1,username=username,userpsd=userpsd)
        # ##数据保存
        # user1.save()
        Users.objects.create(uid=None,username=username,userpsd=userpsd)
    return render(request,'register.html')

def nav(request):
    one = [
           {
               'USP':[
                   {'lol':['rng','ig','jdg','edg']},
                   {'csgo':['c9','tl','faze']},
                   {'apex':['ast','fnc']},
                   {'cf':['g2']},
               ]
           },
           {'AK47': ['aa1', 'bb2', 'cc3']},
           {'M4A1': ['dd4', 'ee5']},
           {'AWP': ['ff6']},
           ]
    return render(request,'nav.html',{'one':one})

def goodinfo(request):
    # 接收前端传递 商品id参数
    gid = request.GET.get('gid')
    # 接收详情页加入购物车传递商品id POST请求
    if request.POST:
        if request.session.get('uid', None):
            gid=request.POST.get('gid')
            uid=request.session['uid']
            car=Cars(gid=gid,buy_count=1,uid=uid)
            car.save()
        else:
            return redirect('/login/')
    # 根据参数执行数据库操作 条件查询 filter
    goods = Goods.objects.filter(gid=gid)
    # 接收 详情页加入购物车传递的参数 商品id
    # car_gid=request.GET.get('car_gid')
    # if car_gid:
    #     # 根据参数执行数据库操作 插入数据
    #     Cars.objects.create(cid=None,gid=car_gid,buy_count=1)
    #     goods=Goods.objects.filter(gid=car_gid)
    return render(request, 'goodinfo.html',{'goods':goods})

def shoppingcar(request):
    # 判断是否登录 用request.session对象中是否存在键uid的值
    if request.session.get('uid',None):# 有值 True 说明登录过
        # 获取 session中的uid
        uid=request.session['uid']
        # 数据库操作 查询操作 购物车表
        cars = Cars.objects.filter(uid=uid)
        # 数据库查询结果 Cars[{cid,gid,buy_count,uid}...]
        goods = [] # 设定响应前端页面的所有购物车数据的列表
        for item in cars: # item{cid,gid,buy_count,uid}
            good = Goods.objects.fliter(gid=item.gid)[0]
            # good {gid,name,price,count,imgsrc,buy_count.allprice}
            good.buy_count = item.buy_count
            good.allprice=good.price*good.buy_count
            goods.append(good)
        return render(request, 'shoppingcar.html',{'goods':goods})
    else:# 无值 False 说明没登录
        return redirect('/login/')

def loginout(request):
    # 业务处理 --> 数据处理
    request.session.clear()
    return redirect('/index/')